import axios from "axios";
import OAuthClient from "axios-oauth-client";

class Auth {
    static authConfig;

    static initToken () {
        const client = axios.create({
            validateStatus (status) {
                return status >= 200 && status < 404;
            }
        });


        this.oauthClient = OAuthClient.client(client, {
            url: "./oauth/token",
            ...this.authConfig
        });

        client.interceptors.response.use((res) => {
            if (res.data && res.data.code && res.data.code !== "CODE_0000") {
                return Promise.reject(res.data.msg);
            }
            return Promise.resolve(res);
        });

        return this.oauthClient().then(tokenInfo => {
            this.setLocalToken(tokenInfo);
            return tokenInfo;
        });
    }

    static checkToken () {
        const tokenInfo = this.getLocalToken();

        // 检查本地 Token 信息是否存在
        if (!tokenInfo) {
            return Promise.reject(false);
        }

        // 通过接口检查 Token 有效性
        const params = new FormData();
        params.append("token", tokenInfo);

        return axios
            .post("./oauth/check_token", params)
            .then(() => {
                return Promise.resolve(true);
            })
            .catch(() => {
                return Promise.reject(false);
            });
    }

    static setLocalToken (tokenInfo) {
        sessionStorage.setItem("access_token", tokenInfo.access_token);
    }

    static getLocalToken () {
        const tokenInfoString = sessionStorage.getItem("access_token");

        if (tokenInfoString) {
            return tokenInfoString
        }

        return null;
    }

    static clearLocalToken () {
        sessionStorage.removeItem("access_token");
    }

    static axiosRequestInterceptor (request) {
        const tokenInfo = Auth.getLocalToken();

        if (tokenInfo) {
            // 添加授权头
            request.headers["Authorization"] = `Bearer ${tokenInfo}`;
        }

        return request;
    }
}

export default Auth;
